<template>
  <div class="card" style="margin-bottom: 5px">
    <el-input clearable @clear="load" style="width: 260px; margin-right: 5px;" v-model="data.title" placeholder="请输入标题查询" :prefix-icon="Search"></el-input>
    <el-button type="primary" @click="load">查 询</el-button>
    <el-button type="info" @click="reset">重 置</el-button>
  </div>
  <div class="card"  style="margin-bottom: 5px" >
    <el-button type="primary" @click="headleAdd">新   增</el-button>
  </div>
  <div class="card" style="margin-bottom: 5px">
    <el-table :data="data.tableData" style="width: 100%" :header-cell-style="{ color:'#333',backgroundColor:'#dde8ff'}">
      <el-table-column label="轮播图" width="100">
        <template #default="scope">
          <el-image :preview-src-list="[scope.row.img]" :preview-teleported="true" v-if="scope.row.img" :src="scope.row.img" alt="" style="width: 50px; height: 50px; display: block; border-radius: 5px"/>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="攻略标题" />
      <el-table-column prop="adminName" label="上传用户" />
      <el-table-column v-if="data.user.role === 'ADMIN'" label="操作" width="100">
        <template #default="scope">
          <el-button type="primary" icon="Edit" circle @click="headleEdit(scope.row)" ></el-button>
          <el-button type="danger" icon="Delete" circle @click="del(scope.row.id)" ></el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="care">
    <el-pagination
        v-model:current-page="data.pageNum"
        v-model:page-size="data.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[5, 10, 15]"
        :total="data.total"
        @current-change="load"
        @size-change="load"
    />
  </div>
  <el-dialog v-model="data.formVisible" title="轮播图信息" destroy-on-close width="60%">
    <el-form ref="formRef" :model="data.form" label-width="80px" style="padding: 20px 30px 10px 0">
      <el-form-item prop="img" label="轮播图" >
        <el-upload
            action="http://localhost:9999/files/upload"
            :headers="{token: data.user.token}"
            :on-success="handleFileSuccess"
            list-type="picture"
        >
          <el-button type="primary">上传头像</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item prop="title" label="轮播标题" >
        <el-input v-model="data.form.title" autocomplete="off" placeholder="请输入轮播标题"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="data.formVisible = false">取消</el-button>
        <el-button type="primary" @click="save">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import request from "@/utils/request.js";
import {Search} from "@element-plus/icons-vue";
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import {onBeforeUnmount, ref, shallowRef, onMounted, reactive} from 'vue'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'

const formRef = ref()
const emit = defineEmits(["updateUser"])
const data = reactive({
  user: JSON.parse(localStorage.getItem('code_user') || '{}'),
  username: '',
  pageNum: 1,
  pageSize: 5,
  total: 6,
  tableData: [],
  title: '',
  formVisible: false,
  form: {},
  contentVisible: false,
  currentContent: '',
  category: [],
})

// 数据获取查询按钮
const load = () => {
  request.get('lunbo/selectAll').then(res => {
    if (res.code === '200') {
      data.category = res.data
      console.log(data.category)
    } else {
      ElMessage.error(res.msg)
    }
  })
  request.get('lunbo/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      title: data.title
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data.list
      data.total = res.data.total
      emit("updateUser")
    } else {
      ElMessage.error(res.msg)
    }
  })
}
load()
// 重置按钮
const reset = () => {
  data.title = ''
  load()
}

// 新增按钮
const headleAdd = () => {
  data.form = {}
  data.formVisible = true
}

//  保存按钮 判断是新增还是修改
const save = () => {
  console.log(data.form)
  if (data.form.id) {
    update()
  } else {
    add()
  }
}

// 新增保存按钮
const add = () => {
  formRef.value.validate(valid => { // formref 是表单的引用 表单验证
    if (!valid) {
      return false
    }
    request.post('lunbo/add', data.form).then(res => {
      if (res.code === '200') {
        data.formVisible = false
        ElMessage.success('新增成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}

// 修改保存按钮
const headleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row)) // 深拷贝
  data.formVisible = true
}

// 删除按钮
const del = (id) => {
  ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '删除确认', {type: 'warning',}).then(res => {
    console.log(id)
    request.delete('/lunbo/delete/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        load()
      }
    }).catch(() => {
      ElMessage.error(res.msg)
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  });
}

// 修改编辑按钮
const update = () => {
  formRef.value.validate(valid => { // formref 是表单的引用 表单验证
    if (!valid) {
      return false
    }
    request.put('lunbo/update', data.form).then(res => {
      if (res.code === '200') {
        data.formVisible = false
        ElMessage.success('修改成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}

const handleFileSuccess = (res) => {
  data.form.img = res.data
}
</script>
<style scoped>

</style>